//
//  VClipIndicatorView.m
//  VChatVideoClip
//
//  Created by huangbolun on 2017/10/9.
//  Copyright © 2017年 huangbolun. All rights reserved.
//

#import "VClipIndicatorView.h"
#import "VVideoClipManger.h"

NSInteger const slideViewW = 20;
NSInteger const lineW = 2;
NSInteger const thumbnailNum = 10;

@interface VClipIndicatorView ()

@property(nonatomic, strong) UIView *thumbnailContainer;

@property(nonatomic, strong) UIView *indicatorContainer;

@property(nonatomic, strong) UIView *coverView;

@property(nonatomic, strong) UIView *leftView;

@property(nonatomic, strong) UIView *rightView;

@property(nonatomic, strong) NSMutableArray *thumbnailImageArray;

@property(nonatomic, strong) UIImageView *currentSelectImageView;

@end

@implementation VClipIndicatorView

- (void)drawRect:(CGRect)rect{
    if (!self.isSelectCover) {
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        [[UIColor colorWithRed:255/255.0 green:190/255.0 blue:6/255.0 alpha:1.0] set];
        CGContextSetLineWidth(ctx, lineW * 2);
        
        CGContextMoveToPoint(ctx, CGRectGetMaxX(self.leftView.frame), 0);
        CGContextAddLineToPoint(ctx, CGRectGetMinX(self.rightView.frame), 0);
        
        CGContextMoveToPoint(ctx, CGRectGetMaxX(self.leftView.frame), self.rightView.frame.size.height);
        
        CGContextAddLineToPoint(ctx, CGRectGetMinX(self.rightView.frame), self.rightView.frame.size.height);
        CGContextStrokePath(ctx);
        
    }
}

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor orangeColor];
        [self setupUI];
    }
    return self;
}

- (void)setupUI{
    [self setupThumbnailContainer];
    [self setupIndicatorContainer];
    [self setupCoverView];
}

- (void)setupThumbnailContainer{
    self.thumbnailContainer = [UIView new];
    [self addSubview:self.thumbnailContainer];
    self.thumbnailContainer.frame = self.bounds;
}

- (void)setupIndicatorContainer{
    self.indicatorContainer = [UIView new];
    [self addSubview:self.indicatorContainer];
    self.indicatorContainer.frame = self.bounds;
    [self setupLeftAndRightIndicator];
}

- (void)setupCoverView{
    self.coverView = [UIView new];
    self.coverView.userInteractionEnabled = NO;
    [self addSubview:self.coverView];
    self.coverView.frame = self.bounds;
    self.coverView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    [self updateMask];
}

- (void)updateMask{
    CGFloat maskW = CGRectGetMaxX(self.rightView.frame) - self.leftView.frame.origin.x;
    CGRect maskRect = CGRectMake(self.leftView.frame.origin.x, self.leftView.frame.origin.y, maskW, self.frame.size.height);
    
    self.coverView.layer.mask = [self maskStyle:maskRect];
}

- (CAShapeLayer *)maskStyle:(CGRect)rect {
  
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.bounds];
    
    UIBezierPath *rectPath = [UIBezierPath bezierPathWithRect:rect];
    [path appendPath:rectPath];
  
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.path = [path CGPath];
    maskLayer.fillRule = kCAFillRuleEvenOdd;
    
    return maskLayer;
}

- (void)setupThumbnailImage{
    Float64 totalDuring = CMTimeGetSeconds(self.asset.duration);
    Float64 delta = totalDuring / thumbnailNum;
    [self.thumbnailImageArray removeAllObjects];
    for (NSInteger i = 0; i < thumbnailNum; i ++) {
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            UIImage *image = [[VVideoClipManger shareClipManger] getVideoPreViewImageWithAsset:(AVURLAsset *)self.asset second:delta * i];
            UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
            if(self.isSelectCover){
                [self.thumbnailImageArray addObject:imageView];
            }
            imageView.backgroundColor = [UIColor yellowColor];
            CGFloat imageW = self.thumbnailContainer.frame.size.width / thumbnailNum;
            imageView.frame = CGRectMake(imageW * i, lineW, imageW, self.thumbnailContainer.frame.size.height - lineW * 2);
            [self.thumbnailContainer addSubview:imageView];
        }];
    }
}

- (void)setupLeftAndRightIndicator{
    UIColor *indecatorColor = [UIColor colorWithRed:255/255.0 green:190/255.0 blue:6/255.0 alpha:1.0];
    
    self.backgroundColor = [UIColor clearColor];
    UIView *leftView = [UIView new];
    self.leftView = leftView;
    [self.indicatorContainer addSubview:leftView];
    leftView.frame = CGRectMake(0, 0, slideViewW, self.frame.size.height);
    leftView.backgroundColor = indecatorColor;
    [leftView addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(onLeftViewMovie:)]];
    
    UIView *rightView = [UIView new];
    self.rightView = rightView;
    [self.indicatorContainer addSubview:rightView];
    rightView.frame = CGRectMake(self.frame.size.width - slideViewW, 0, slideViewW, self.frame.size.height);
    rightView.backgroundColor = indecatorColor;
    
    [rightView addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(onRightViewMovie:)]];
}

#pragma mark - Action
- (void)onLeftViewMovie:(UIPanGestureRecognizer *)pan{
    CGPoint curentPoint = [pan locationInView:self];
    self.leftView.center = CGPointMake(curentPoint.x, self.leftView.center.y);
    if(self.leftView.frame.origin.x <= 0){
        self.leftView.center = CGPointMake(slideViewW/2, self.leftView.center.y);
    }else if(CGRectGetMaxX(self.leftView.frame) >= CGRectGetMinX(self.rightView.frame)){
        self.leftView.center = CGPointMake(CGRectGetMinX(self.rightView.frame) - (slideViewW/2), self.leftView.center.y);
    }
    
    [self indicatorChangedWithX:self.leftView.center.x isLeft:YES];
    if (pan.state == UIGestureRecognizerStateEnded) {
        [self indicatorEnd];
    }
}

- (void)onRightViewMovie:(UIPanGestureRecognizer *)pan{
    CGPoint curentPoint = [pan locationInView:self];
    self.rightView.center = CGPointMake(curentPoint.x, self.rightView.center.y);
    if(self.rightView.frame.origin.x <= CGRectGetMaxX(self.leftView.frame)){
        self.rightView.center = CGPointMake(CGRectGetMaxX(self.leftView.frame) + slideViewW/2, self.leftView.center.y);
    }else if(CGRectGetMaxX(self.rightView.frame) >= self.frame.size.width){
        self.rightView.center = CGPointMake(self.frame.size.width - (slideViewW/2), self.rightView.center.y);
    }
    [self indicatorChangedWithX:self.rightView.center.x isLeft:NO];
    if (pan.state == UIGestureRecognizerStateEnded) {
        [self indicatorEnd];
    }
}

- (void)indicatorChangedWithX:(CGFloat)value isLeft:(BOOL)isLeft{
    CGFloat total = self.frame.size.width - slideViewW;
    CGFloat resultValue = (value - slideViewW / 2) / total;
    [self setNeedsDisplay];
    if ([self.delegate respondsToSelector:@selector(onIndicatorChanged:isLeft:)]) {
        [self.delegate onIndicatorChanged:resultValue isLeft:isLeft];
    }
    [self updateMask];
}

- (void)indicatorEnd{
    CGFloat total = self.frame.size.width - slideViewW;
    CGFloat leftValue = (self.leftView.center.x - slideViewW/2) / total;
    CGFloat rightValue = (self.rightView.center.x - slideViewW/2) / total;
    [self setNeedsDisplay];
    if ([self.delegate respondsToSelector:@selector(onIndicatorEndWithLeft:right:)]) {
        [self.delegate onIndicatorEndWithLeft:leftValue right:rightValue];
    }
}

- (void)onImgeSelected:(UITapGestureRecognizer *)tap{
    CGPoint currentPoint = [tap locationInView:tap.view];
    
    CGFloat cellW = self.thumbnailContainer.frame.size.width / thumbnailNum;
    NSInteger index = currentPoint.x / cellW;
    if (index > self.thumbnailImageArray.count - 1 || index < 0) {
        NSLog(@"video: %zd -- %zd",index,self.thumbnailImageArray.count);
        return;
    }
    UIImageView *selectImageView = self.thumbnailImageArray[index];
    self.currentSelectImageView.layer.borderColor = [UIColor clearColor].CGColor;
    self.currentSelectImageView.layer.borderWidth = 0;
    self.currentSelectImageView = selectImageView;
    selectImageView.layer.borderColor = [UIColor colorWithRed:255/255.0 green:190/255.0 blue:6/255.0 alpha:1.0].CGColor;
    selectImageView.layer.borderWidth = 2;
    
    
    if ([self.delegate respondsToSelector:@selector(onSelectImage:)]) {
        [self.delegate onSelectImage:selectImageView.image];
    }
    
}

#pragma mark - Set
- (void)setAsset:(AVAsset *)asset{
    _asset = asset;
    [self setupThumbnailImage];
}

- (void)setIsSelectCover:(BOOL)isSelectCover{
    _isSelectCover = isSelectCover;
    if (isSelectCover) {
        self.indicatorContainer.hidden = YES;
        [self.thumbnailContainer addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onImgeSelected:)]];
    }else{
        self.indicatorContainer.hidden = NO;
    }
}

#pragma mark - Lazy
- (NSMutableArray *)thumbnailImageArray{
    if (!_thumbnailImageArray) {
        _thumbnailImageArray = [NSMutableArray arrayWithCapacity:thumbnailNum];
    }
    return _thumbnailImageArray;
}

@end
